package TongHuaShun

import (
	"errors"
	"fmt"
	"get"
	"git.oschina.net/OO-o/stock/base"
	"git.oschina.net/OO-o/stock/model"
	"strconv"
	"strings"
	"sync"
)

type Day_TongHuaShun struct {
	Code string
	Name string
	Data [][]string
}

func StringTofloat64(s string) float64 {
	f, _ := strconv.ParseFloat(s, 64)
	return f
}
func (d *Day_TongHuaShun) ToData() *model.Data {

	var C = make([]float64, 0, len(d.Data))
	var H = make([]float64, 0, len(d.Data))
	var L = make([]float64, 0, len(d.Data))
	var Date = make([]string, 0, len(d.Data))
	for i := 0; i < len(d.Data); i++ {
		Date = append(Date, d.Data[i][0])
		C = append(C, StringTofloat64(d.Data[i][4]))
		H = append(H, StringTofloat64(d.Data[i][2]))
		L = append(L, StringTofloat64(d.Data[i][3]))

	}
	Datas := &model.Data{
		Code: d.Code,
		Name: d.Name,
		C:    &base.Base{},
		H:    &base.Base{},
		L:    &base.Base{},

		Date: Date,
	}
	Datas.C.Set(C)
	Datas.H.Set(H)
	Datas.L.Set(L)
	//fmt.Println(len(Datas.Date) == len(Datas.C.Value()))
	/*	for i := len(Date) - 1; i > 0; i-- {
		fmt.Println(Date[i], "----", Datas.C.I(i), "-----", Datas.H.I(i), "-------", Datas.L.I(i))
	}*/

	return Datas
}
func NewTHS_Day(code string) (*Day_TongHuaShun, error) {
	if code[0] == '0' || code[0] == '3' {
		code = "sz_" + code
	} else {
		code = "sh_" + code
	}
	url := "http://qd.10jqka.com.cn/api.php?p=stock_day&year=2014,2015&fq=&info=k_" + code
	body, err := get.Get(url)
	if err != nil {
		return nil, err

	}
	if !strings.Contains(body, "|") || !strings.Contains(body, ",") {
		//	fmt.Println("没有内容！")
		return nil, errors.New(" 没有内容！")
	}
	var Data Day_TongHuaShun
	first := strings.Split(body, ";")
	var total string
	for i := 0; i < len(first); i++ {
		total += strings.Split(first[i], "=")[1]
	}
	//fmt.Println(total)
	Data.Code = code[3:]
	Data.Name = code[3:]
	D := strings.Split(total, "|")
	//fmt.Println("数据个数：", len(D))
	s := make([][]string, 0, len(D)-1)
	for i := 0; i < len(D)-1; i++ {

		DD := strings.Split(D[i], ",")
		//	fmt.Println(DD)
		if len(DD) != 7 {
			fmt.Println("数据不等于7")
			fmt.Println(len(DD))
			return nil, errors.New("n e 7")
		}

		s = append(s, DD)
	}
	//fmt.Println("得到的数据数量：", len(s))
	Data.Data = s
	//fmt.Println("Data", Data)
	return &Data, nil

}
func Run(codes []string, GoNub, nub int) {
	var wait sync.WaitGroup
	c := make(chan string)
	wait.Add(GoNub)
	for i := 0; i < GoNub; i++ {
		go func() {
			for item := range c {
				info := Do(item, nub)
				if len(info) > 0 {
					fmt.Println("info:", info)
				}
				//fmt.Println("处理Over：", item)
			}
			wait.Done()

		}()
	}
	for _, item := range codes {
		c <- item
	}
	close(c)
	wait.Wait()
}
func Do(Code string, nub int) []model.Info {
	Data, err := NewTHS_Day(Code)
	if err != nil {
		return nil
	}
	return model.Model003(Data, nub)
}
